var forword = encodeURIComponent(window.location.href);
var backUrl = $.getUrlVar("back");

var vm=new Vue({
  el:"#app",
  data:{
    title:'',
    tabs:0,
    infos:[],
    topics:[],
    asks:[],
    user:{},
    isTrue:false,
    isLoading:true,
    pageSize:PAGESIZE,
    pageIndex:1,
    willShow:'myCenter',
    typeID:0,
    value:'',
    name:'',
    goldList:[],
    circle:[],
    reqOut: false, //判断请求数据是否已完
    
    inputText:'',
    showModal:false,
    shareObj:{
      dataID:'',
      shareTit:'',
      sharePic:''
    }
  },
  created:function(){
    var _self = this;
    // 顶部个人信息
    Common.ajaxCall({ url: "user_getUserDetailInfo", datatype: 'json', type: 'post'}, function (data) {
      if(data.error_code==0){
          _self.user=data.data;
        
      }else{
          alert(data.msg);
      }
    });
    $(window).scroll(function() {
        var topH = $(window).scrollTop();
        var userH = $('.vault').height();
        if (topH > userH) {
            $('.tabFixed').addClass('top');
            $('.tabBox').css('padding-top', $('.tabFixed').outerHeight());
        } else {
            $('.tabFixed').removeClass('top');
            $('.tabBox').css('padding-top', '0');
        }
    });
  },
  compiled: function(){
      var _self = this;
      var top = $(document).scrollTop();
      $(document).scroll(function () {
        if(top!=$(document).scrollTop()){
          // 上下滚动
          var docHeight = $(document).height(),
              winHeight = $(window).height();
          if ((docHeight > winHeight)&&($(document).scrollTop() >= docHeight - winHeight)) {
              if (!_self.reqOut) {
                  _self.reqOut = true;
                  var str = '<img class="loading-img" src="images/loading.gif"></img>';
                  myLoad.pullLoad('quesCont', str);
                  _self.willShow === 'modify' ? '' : _self.loadlist(_self.tabs);

              }
          }
        }else{
            // 左右滚动
        }
      });

      $(document).on('change.inputText','.fillInput',function(){
          _self.inputText = $(this).val();
      });

      _self.loadlist(_self.tabs);
  },
  methods:{
    loadlist:function(tabs){
      var _self = this;
      var vModal,target;  //用来储存不同的tab页面对应的对象
      switch(tabs){       //根据tab的切换来设置sortType的值
        case 0:
          // 文档
          var url = 'user_getMyArticle';
          var data = {
            pageSize:_self.pageSize,
            pageIndex:_self.pageIndex
          } 
          
          vModal = _self;
          target = _self.infos;
        break;
        case 1:// 话题
          var url = 'user_getMyTopic';
          var data = {
            pageSize:_self.pageSize,
            pageIndex:_self.pageIndex
          }; 

          vModal = _self;
          target = _self.topics;
        break;
        case 2:// 提问
          var url = 'user_getMyAsk';
          var data = {
            pageSize:_self.pageSize,
            pageIndex:_self.pageIndex
          }; 

          vModal = _self;
          target = _self.asks;
        break;
        case 3:
          var url = 'user_getMyAnswer';
          var data = {
            pageSize:_self.pageSize,
            pageIndex:_self.pageIndex
          }; 

          vModal = _self;
          target = _self.asks;
        break;
        case 4:  // 查看加入的圈子
          var url = 'user_getMyCircle';
          var data = {
            pageSize: PAGESIZE,
            pageIndex: 1
          }; 

          vModal = _self;
          target = _self.circle;
          
        break;
        /*case 5:  // 白金币记录
          var url = 'user_getGoldHistoryList';
          var data = {
            pageSize:_self.pageSize,
            pageIndex:_self.pageIndex
          }; 

          vModal = _self;
          target = _self.goldList;
          
        break;*/
        default:
           
        break; 
      }

      if(!vModal.isLoading) return;
      data = Common.jsonEncode(data);
      Common.ajaxCall({ url: url, datatype: 'json', type: 'post', data: data}, function (data) {
          if(data.error_code==0 && data.data.length > 0){
              if(vModal.pageIndex==1){
                target.length = 0;
              }
              for(var i = 0; i < data.data.length; i++){
                target.push(data.data[i]);
              }
              _self.reqOut = false;

              //实际数据与请求的数据量比较
              if (data.data.length >= vModal.pageSize) {
                  myLoad.pullHide(); //加载后，把效果去掉
              } else {
                  _self.reqOut = true;
                  myLoad.noDate(); //暂无数据
                  vModal.isLoading = false;
              }
              
          }else{
              _self.reqOut = true;
              myLoad.noDate(); //暂无数据
              vModal.isLoading = false;
          }

          vModal.pageIndex++;
      });
      
    },
    toCircleList:function(id){
      window.location.href = "circleList.html?id=" + id + "&back=" + forword;
    },
    toArticleDetail:function(id){
      window.location.href = "articleDetail.html?id=" + id + "&back=" + forword;
    },
    toCircleDetail:function(id){
      window.location.href = "circleDetail.html?id=" + id + "&back=" + forword;
    },
    toAskDetail:function(id){
      window.location.href = "askDetail.html?id=" + id + "&back=" + forword;
    },
    back:function(){
      var _self = this;
      _self.reqOut = false;
      _self.isLoading = true;
      if(this.willShow === 'modifyText'){
        this.willShow = 'modify';
        $("#huserName").show();
      }else if(this.willShow !== 'myCenter'){
        this.willShow = 'myCenter';
        _self.user.userName = _self.title;  //重新显示用户名
        //重置tabs
        _self.tabs = 0;
        $('.quesTab li').eq(_self.tabs).addClass('on').siblings().removeClass('on');
        _self.loadlist(_self.tabs);

      }else{
        window.location.href = decodeURIComponent(backUrl);
      }
      
    },
    confirm:function(){
      //确认修改
      var _self = this;
      var value = $("#title").val();
      if(value==""){
        alert('请输入');
        return;
      }
      
      var data = {
        typeID:_self.typeID,
        value:value
      };
      //data[_self.typeID] = value;
      
      data = Common.jsonEncode(data);
      Common.ajaxCall({ url: 'user_updateUserInfo', datatype: 'json', type: 'get', data: data}, function (data) {
          alert(data.msg);
          if(data.error_code==0){
            //延迟跳转
            _self.user[_self.name] = value;
            setTimeout(function(){ _self.willShow='modify';},1000);
          }
      });
    },
    fn:function(flag,uid){
      var _self = this;
      _self.title = _self.user.userName;

      switch(flag){
        case 'dynamic':
          window.location.href = "dynamicKnowledge.html?&back="+forword;

        break;
        case 'record':
          /*this.willShow = flag;
          this.user.userName='白金币记录';
          _self.tabs = 4;   //查看白金币记录
          _self.loadlist(_self.tabs);*/
          window.location.href = "myRecord.html?back="+forword;

        break;
        case 'collect':
          //this.willShow = flag;
          window.location.href = "myCollect.html?back="+forword;
        break;
        case 'community':
          this.willShow = flag;
          _self.tabs = 5;   //查看加入圈子
          _self.circle = [];
          _self.isLoading = true;

          _self.loadlist(_self.tabs);
        break;
        case 'modify':
          
          _self.willShow = flag;
          $('.userModify li').bind('click',function(){
            //console.log($(this).index());
            var e = $(this).find('input');
            if(e.data('modifiable')){
              _self.willShow = 'modifyText';
              $("#huserName").hide();

              _self.name = e.attr('name');
              _self.value = e.val();
              _self.typeID = e.attr('name'); //将要修改的字段保存下来
            }
          });
        break;
      }
    },
    slides:function(index,e){
        var _self = this;
        _self.tabs = index;
        
        $(e.currentTarget).addClass('on').siblings().removeClass('on');
        
        var data = {
          isLoading:true,
          pageSize:PAGESIZE,
          pageIndex:1,
          infos:[],
          asks:[],
          topics:[]
        };
        _self = $.extend(_self,data);

        _self.loadlist(_self.tabs);
    },
    swipeLeft: function (e) {
        var _self = this;
        if(_self.isEdit==='取消') return;  //如果处于编辑状态则不予左滑

        var shareColl = $(e.target).parents('li');
        var touchDrift = ($(e.target).parents('li').width())/3;
        var drift = ($(e.target).parents('li').width())/3;
        //回复原位置
        _self.isDrift = false;  //标识为非左滑状态
        $(e.target).parents('ul').children().animate({left:0});
        $(e.target).parents('ul').children().find('.shareColl').animate({width:0,right:0});
        

        console.log(e.deltaX);
        if(e.deltaX<0){      //左滑
          _self.isDrift = true;  //标识为左滑状态
          if(e.deltaX < -touchDrift){
            $(e.target).parents('li').animate({left:-drift});
            var height = $(e.target).parents('li').outerHeight();
            shareColl.find('.shareColl').animate({width:drift,right:-drift}).show().css('line-height',height + 'px');
          }
        }else{               //右滑
          if(e.deltaX > touchDrift){
            _self.isDrift = false;  //标识为非左滑状态
            $(e.target).parents('li').animate({left:0});
            shareColl.find('.shareColl').fadeOut();
            
          }
        }
      },
      share:function(obj,e){
          $(e.target).parents('li').animate({left:0}).find('.shareColl').fadeOut(); //将左滑的元素复位
          var _self = this;
          _self.showModal = true;
          console.log(obj);
          _self.shareObj = {
            dataID : obj.shareId, //文档id
            shareTit : obj.shareTit, //文档标题
            sharePic : obj.sharePic,    //文档图片
            isdoc : obj.isdoc   //是不是文档
          };
          
      },
      shareReg:function(userList){
          var _self = this;
          if(!userList){     //如果没选择分享对象回到原来界面
            _self.showModal = false;
            return;
          }
          var scale;
          _self.shareObj.isdoc ? scale="s_34" : scale="s_1";
          alert({
              close: false,
              text: '分享',
              description: '<div class="clearfix shareTxt"><span class="j_1 photo"><img class="'+ scale +'" src="'+Common.wordIcon(_self.shareObj.sharePic,_self.shareObj.isdoc) +'" onerror=\"javascript:this.src=\'images/icon/type/OTHER.png\';this.onerror=null;\"></span><span class="text">'+_self.shareObj.shareTit+'</span></div>',
              fillInput: true,
              kind: 2,
              okEvent: function(){
                  var data = {
                      dataID: _self.shareObj.dataID,
                      userList : userList,
                      comment:_self.inputText,
                      type:2
                  };
                  data = Common.jsonEncode(data);
                  Common.ajaxCall({ url: 'look_share', datatype: 'json', type: 'get', data: data}, function (data) {
                      if(data.error_code==0){
                          var obj = data.data[0];
                          var code = obj.code;
                          var pic = code==1?"moneyPig.png":"lebel.png";
                          alert({
                              text: '<img src="images/'+pic+'"/>',
                              description: obj.str,
                              kind: 0
                          });
                      }else{
                          alert(data.msg);
                      }
                  });
              }
          });
      },
      //收藏
      Collection:function(obj,e){
          var _self = this;
          _self.addShow = false;
          $(e.target).parents('li').animate({left:0}).find('.shareColl').fadeOut(); //将左滑的元素复位
          var data = {
              dataID: obj.dataID,
              type : 2,
              isCollection:1
          };
          data = Common.jsonEncode(data);
          Common.ajaxCall({ url: 'look_addCollection', datatype: 'json', type: 'get', data: data}, function (data) {
              if(data.error_code==0){
                  var obj = data.data[0];
                  var code = obj.code;
                  var pic = code==1?"moneyPig.png":"lebel.png";
                  alert({
                      text: '<img src="images/'+pic+'"/>',
                      description: obj.str,
                      kind: 0
                  });
              }else{
                  alert(data.msg);
              }
          });
      },
      doDel:function(options){   //删除
      var _self = this;
      var dataID = [],type;

      /*将tab数与type数对应*/
      _self.tabs===0 ? type=1 : _self.tabs === 1 ? type=2 : _self.tabs === 2 ? type=3 : type=4;
      
      //console.log($('.edit').hasClass('on'));
      [].forEach.call($('.edit'),function(val,index,context){
          var $val = $(val);
          if($val.hasClass('on')){
            dataID.push($val.parents('li').data('id'));
          }
      });
      if(options){
        var data = {
          id : options.dataID,
          type : type
        }
      }else{
        if(dataID.length === 0){
          alert('您没有作任何选择！');
          return;
        }
        var data = {
          dataID : dataID.join(','),
          type : type
        }
      }

      data = Common.jsonEncode(data);
      Common.ajaxCall({ url: 'user_delMyInfo', datatype: 'json', type: 'get', data: data}, function (data) {
          if(data.error_code==0){
              alert(data.msg);

              //_self.isEdit = '编辑'; //将状态复原
              _self.isDrift = false;

              _self.infos = [];
              _self.topics = [];
              _self.asks = [];

              _self.isLoading = true;
              _self.pageSize = PAGESIZE;
              _self.pageIndex = 1;

              _self.loadlist(_self.tabs);
          }else{
              alert(data.msg);
          }
      });
    },
    loadPhoto:function(){
      // 轮播比例
      myJS.imgScale('.j_1', '1', '1');
      myJS.imgScale('.j_6', '6', '5');
      myJS.ImgFull('.loadImg','images/liby.png');
    }
  },
  watch:{
    "circle": function(){
      this.loadPhoto();
    },
    "topics": function(){
      this.loadPhoto();
    }
  }
});